package com.se.net;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.*;
import com.sun.jna.ptr.IntByReference;

//根据PID获取进程名   /proc/pid/status
public class ProcessNameFinder {

    //Psapi.GetProcessImageFileName  PsapiUtil  Kernel32Util.QueryFullProcessImageName
    public static void main(String[] args) {

        //clash
        int targetPid = 6768;
        int pid = 14072;

        String processName = getProcessName(targetPid);


        System.err.println("Process name for PID: " + targetPid + ": " + processName);
    }

    @Deprecated
    private static String getProcessName(int pid) {

        Kernel32 kernel32 = Kernel32.INSTANCE;
        WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));

        try {
            Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
            IntByReference pidRef = new IntByReference(pid);

            while (kernel32.Process32Next(snapshot, processEntry)) {

                System.out.println(Native.toString(processEntry.szExeFile));

                if (processEntry.th32ProcessID.intValue() == pid) {
                    return Native.toString(processEntry.szExeFile);
                }
            }
        } finally {
            kernel32.CloseHandle(snapshot);
        }

        return null; // Process not found
    }
}
